﻿using NPOI.HSSF.UserModel;
using OMG.Fill.Potato.Model.Ent;
using OMG.Fill.Potato.Services;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Http;
namespace OMG.Fill.Potato.Model.UI.Controllers
{
    public class PotSaleStoregeController : ApiController
    {
        PotSaleStoregeServices potSaleStoregeServices = new PotSaleStoregeServices();
        
        //[ApiActionAuthorize("获取马铃薯销售、存储与加工情况统计表分页列表对象操作")]
        //[ApiActionException]
        public Pager<List<PotSaleStoregeEntity>> PostPageList(PotSaleStoregeQuery query)
        {
            return potSaleStoregeServices.GetPageList(query);
        }
        //[ApiActionAuthorize("新增马铃薯销售、存储与加工情况统计表指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Post(PotSaleStoregeEntity model) {
            return potSaleStoregeServices.AddInfo(model);
        }
        //[ApiActionAuthorize("修改马铃薯销售、存储与加工情况统计表指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Put(PotSaleStoregeEntity model)
        {
            return potSaleStoregeServices.UpdateInfo(model);
        }
        //[ApiActionAuthorize("删除马铃薯销售、存储与加工情况统计表指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Delete(string id)
        {
            return potSaleStoregeServices.DeleteInfo(id);
        }
        //[ApiActionAuthorize("获取马铃薯销售、存储与加工情况统计表指定对象操作")]
        //[ApiActionException]
        public ResResult<SaleStoregeFillInModel> Get(string AreaCode,string FillInYear)
        {
            return potSaleStoregeServices.GetModel(AreaCode,FillInYear);
        }
        public ResResult<PotSaleStoregeEntity> GetDataModel(string ReportId)
        {
            return potSaleStoregeServices.GetDataModel(ReportId);
        }

        public ResResult<List<List<AllYearStatisModel>>> GetAllYearStatisList(string AreaCode)
        {
            return potSaleStoregeServices.GetAllYearStatisList(AreaCode);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="ReportId"></param>
        /// <param name="FillInYear"></param>
        /// <param name="AreaName"></param>
        public void GetExcelData(string AreaCode, string FillInYear)
        {
            AreaServices areaServices = new AreaServices();
            string AreaName = areaServices.GetByCodeModel(AreaCode).model.Name;
            //打开完成excel文件并下载
            HttpContext curContext = HttpContext.Current;
            // 设置编码和附件格式
            curContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";
            string strFileName = "（五）" + FillInYear + "年" + "-" + AreaName + "-马铃薯销售、存储与加工情况统计表.xls";
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
            curContext.Response.BinaryWrite(Method(AreaCode, FillInYear).GetBuffer());
            curContext.Response.End();
        }
        /// <summary>
        /// 获取导出数据
        /// </summary>
        /// <param name="ReportId"></param>
        /// <returns></returns>
        public MemoryStream Method(string AreaCode, string FillInYear)
        {
            FileStream file = null;
            MemoryStream ms = new MemoryStream();
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\PotDownload.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet sheet = templateBook.GetSheet("PotSaleStorege") as HSSFSheet;//读取模板所在sheet位置
           PotSaleStoregeEntity datamodel = potSaleStoregeServices.GetModel(AreaCode, FillInYear).model.DataModel;//数据获取
            try
            {
                if (datamodel != null)
                {
                    HSSFRow row = (HSSFRow)sheet.GetRow(4);//读取模板第5行                   
                    int startRow = 4;                   
                        HSSFRow datarow = (HSSFRow)sheet.CreateRow(startRow);
                        datarow.CreateCell(0).SetCellValue(datamodel.ProductYield == null ? "" : string.Format("{0:N4}", datamodel.ProductYield));
                        datarow.CreateCell(1).SetCellValue(datamodel.SaleYield == null ? "" : string.Format("{0:N4}", datamodel.SaleYield));
                        datarow.CreateCell(2).SetCellValue(datamodel.PecSaleYield == null ? "" : string.Format("{0:N2}", datamodel.PecSaleYield));
                        datarow.CreateCell(3).SetCellValue(datamodel.ZLyield == null ? "" : string.Format("{0:N4}", datamodel.ZLyield));
                        datarow.CreateCell(4).SetCellValue(datamodel.XSyield == null ? "" : string.Format("{0:N4}", datamodel.XSyield));
                        datarow.CreateCell(5).SetCellValue(datamodel.SYyield == null ? "" : string.Format("{0:N4}", datamodel.SYyield));
                        datarow.CreateCell(6).SetCellValue(datamodel.ZSyield == null ? "" : string.Format("{0:N4}", datamodel.ZSyield));
                        datarow.CreateCell(7).SetCellValue(datamodel.ProductOutput == null ? "" : string.Format("{0:N4}", datamodel.ProductOutput));
                        datarow.CreateCell(8).SetCellValue(datamodel.SaleOutput == null ? "" : string.Format("{0:N4}", datamodel.SaleOutput));
                        datarow.CreateCell(9).SetCellValue(datamodel.PecSaleOutput == null ? "" : string.Format("{0:N2}", datamodel.PecSaleOutput));
                        datarow.CreateCell(10).SetCellValue(datamodel.SaleZone == null ? "" : datamodel.SaleZone);
                        datarow.CreateCell(11).SetCellValue(datamodel.StorageNum == null ? "" : string.Format("{0:N4}", datamodel.StorageNum));
                        datarow.CreateCell(12).SetCellValue(datamodel.StorageWay == null ? "" : datamodel.StorageWay);
                        datarow.CreateCell(13).SetCellValue(datamodel.Stock == null ? "" : string.Format("{0:N4}", datamodel.Stock));
                        datarow.CreateCell(14).SetCellValue(datamodel.DFyield == null ? "" : string.Format("{0:N4}", datamodel.DFyield));
                        datarow.CreateCell(15).SetCellValue(datamodel.DFoutput == null ? "" : string.Format("{0:N4}", datamodel.DFoutput));
                        datarow.CreateCell(16).SetCellValue(datamodel.SPyield == null ? "" : string.Format("{0:N4}", datamodel.SPyield));
                        datarow.CreateCell(17).SetCellValue(datamodel.SPoutput == null ? "" : string.Format("{0:N4}", datamodel.SPoutput));
                        datarow.CreateCell(18).SetCellValue(datamodel.OPyield == null ? "" : string.Format("{0:N4}", datamodel.OPyield));
                        datarow.CreateCell(19).SetCellValue(datamodel.OPoutput == null ? "" : string.Format("{0:N4}", datamodel.OPoutput));
                        datarow.CreateCell(20).SetCellValue(datamodel.Remark == null ? "" :datamodel.Remark);           
                                
                        for (int i = 0; i <= 20; i++)
                        {
                            datarow.GetCell(i).CellStyle = row.GetCell(i).CellStyle;
                        }
                    
                    sheet.CopyTo(workbook, "Sheet1", true, true);
                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;

                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.ToString().Trim());
            }
            return ms;
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="ReportId"></param>
        /// <returns></returns>
        public ResResult<int> PostImportData(string ReportId)
        {
            ResResult<int> obj = new ResResult<int>();
            ResResult<int> SingleObj = new ResResult<int>();
            HttpContext curContext = HttpContext.Current;
            HttpFileCollection files = curContext.Request.Files;

            if (curContext.Request.Files.Count != 0)
            {
                HttpPostedFile upfile = files[0];
                if (upfile != null && upfile.ContentLength > 0)
                {
                    string temppath = curContext.Server.MapPath("~/App_Data/temppath");
                    if (!Directory.Exists(temppath))//判断文件夹是否存在 
                    {
                        Directory.CreateDirectory(temppath);//不存在则创建文件夹 
                    }
                    string filetype = Path.GetExtension(upfile.FileName);
                    string filenewName = Guid.NewGuid().ToString().Replace("-", "") + filetype;
                    string strpath = Path.Combine(temppath, filenewName);
                    upfile.SaveAs(strpath);
                   PotSaleStoregeEntity model = potSaleStoregeServices.ExcelToModel(strpath, filetype, ReportId);
                    if (model != null && potSaleStoregeServices.UpdateInfo(model).status== DefaultKey.SuccessResult)
                    {
                        obj.status = DefaultKey.SuccessResult; ;
                        obj.message = "数据导入成功！！";
                    }
                    else
                    {
                        obj.status = DefaultKey.ErrorResult; ;
                        obj.message = "数据导入失败！！";
                    }
                    Directory.Delete(temppath, true);
                }
            }

            return obj;
        }
        /// <summary>
        /// 获取统计列表
        /// </summary>
        /// <param name="AreaCode"></param>
        /// <param name="FillInYear"></param>
        /// <returns></returns>
        public ResResult<List<SaleStoregeStatisModel>> GetStatisListData(string AreaCode, string FillInYear)
        {
            return potSaleStoregeServices.getStatisListData(AreaCode, FillInYear);
        }

        /// <summary>
        /// 统计导出
        /// </summary>
        /// <param name="AreaCode"></param>
        /// <param name="FillInYear"></param>
        public void GetStatisExcel(string AreaCode, string FillInYear)
        {
            AreaServices areaServices = new AreaServices();
            string AreaName = areaServices.GetByCodeModel(AreaCode).model.Name;
            //打开完成excel文件并下载
            HttpContext curContext = HttpContext.Current;
            // 设置编码和附件格式
            curContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";
            string strFileName = "（五）" + FillInYear + "年" + "-" + AreaName + "-马铃薯销售、存储与加工情况统计汇总表.xls";
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
            //curContext.Response.AppendHeader("Content-Disposition",
            //   "attachment;filename=" + strFileName);
            curContext.Response.BinaryWrite(loadStatis(AreaCode, FillInYear).GetBuffer());
            curContext.Response.End();
        }

        public MemoryStream loadStatis(string AreaCode, string FillInYear)
        {
            FileStream file = null;
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\PotStatisLoad.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet tempsheet = templateBook.GetSheet("PotSaleStorege") as HSSFSheet;//读取模板所在sheet位置
            List<SaleStoregeStatisModel> pagelist = (List<SaleStoregeStatisModel>)potSaleStoregeServices.getStatisListData(AreaCode, FillInYear).model;//数据获取

            HSSFRow row = (HSSFRow)tempsheet.GetRow(4);//读取模板第5行
            var style = row.GetCell(1).CellStyle;//读取模板第5行第2单元格样式并保存
            row.GetCell(1).CellStyle = style;//对第3行第2单元格设置原来样式

            HSSFSheet sheet = CopyToSheet(tempsheet, pagelist);
            AreaServices areaServices = new AreaServices();
            string areaName = areaServices.GetByCodeModel(AreaCode).model.Name;
            sheet.CopyTo(workbook, areaName, true, true);
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms;
            }
        }

        public HSSFSheet CopyToSheet(HSSFSheet sheet, List<SaleStoregeStatisModel> list)
        {
            HSSFRow row = (HSSFRow)sheet.GetRow(4);
            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    HSSFRow datarow = (HSSFRow)sheet.CreateRow(4 + i);
                    datarow.CreateCell(0).SetCellValue(list[i].AreaName == null ? "" : list[i].AreaName);
                    datarow.CreateCell(1).SetCellValue(list[i].ProductYield == null ? "" : string.Format("{0:N4}", list[i].ProductYield));
                    datarow.CreateCell(2).SetCellValue(list[i].SaleYield == null ? "" : string.Format("{0:N4}", list[i].SaleYield));
                    datarow.CreateCell(3).SetCellValue(list[i].PecSaleYield == null ? "" : string.Format("{0:N2}", list[i].PecSaleYield));
                    datarow.CreateCell(4).SetCellValue(list[i].ZLyield == null ? "" : string.Format("{0:N4}", list[i].ZLyield));
                    datarow.CreateCell(5).SetCellValue(list[i].XSyield == null ? "" : string.Format("{0:N4}", list[i].XSyield));
                    datarow.CreateCell(6).SetCellValue(list[i].SYyield == null ? "" : string.Format("{0:N4}", list[i].SYyield));
                    datarow.CreateCell(7).SetCellValue(list[i].ZSyield == null ? "" : string.Format("{0:N4}", list[i].ZSyield));
                    datarow.CreateCell(8).SetCellValue(list[i].ProductOutput == null ? "" : string.Format("{0:N4}", list[i].ProductOutput));
                    datarow.CreateCell(9).SetCellValue(list[i].SaleOutput == null ? "" : string.Format("{0:N4}", list[i].SaleOutput));
                    datarow.CreateCell(10).SetCellValue(list[i].PecSaleOutput == null ? "" : string.Format("{0:N2}", list[i].PecSaleOutput));
                    datarow.CreateCell(11).SetCellValue(list[i].StorageNum == null ? "" : string.Format("{0:N4}", list[i].StorageNum));
                    datarow.CreateCell(12).SetCellValue(list[i].Stock == null ? "" : string.Format("{0:N4}", list[i].Stock));
                    datarow.CreateCell(13).SetCellValue(list[i].DFyield == null ? "" : string.Format("{0:N4}", list[i].DFyield));
                    datarow.CreateCell(14).SetCellValue(list[i].DFoutput == null ? "" : string.Format("{0:N4}", list[i].DFoutput));
                    datarow.CreateCell(15).SetCellValue(list[i].SPyield == null ? "" : string.Format("{0:N4}", list[i].SPyield));
                    datarow.CreateCell(16).SetCellValue(list[i].SPoutput == null ? "" : string.Format("{0:N4}", list[i].SPoutput));
                    datarow.CreateCell(17).SetCellValue(list[i].OPyield == null ? "" : string.Format("{0:N4}", list[i].OPyield));
                    datarow.CreateCell(18).SetCellValue(list[i].OPoutput == null ? "" : string.Format("{0:N4}", list[i].OPoutput));

                    for (int j = 0; j <= 18; j++)
                    {
                        datarow.GetCell(j).CellStyle = row.GetCell(j).CellStyle;
                    }

                }
            }
            return sheet;
        }



    }
}